package com.qiangqiang.resoldhouse.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qiangqiang.resoldhouse.dto.EstateDTO;
import com.qiangqiang.resoldhouse.dto.PageDTO;
import com.qiangqiang.resoldhouse.entity.Estate;
import com.qiangqiang.resoldhouse.entity.EstateSelect;
import com.qiangqiang.resoldhouse.mapper.EstateMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: zqh
 * @date: 2018/8/9 15:47
 * @description:
 */
@Service
public class EstateService {

    @Autowired
    private EstateMapper mapper;

    public EstateDTO findEstateById(Long estateId){
        return beanToDTO(mapper.selectById(estateId));
    }

    //取得所有小区
    public List<EstateDTO> findAllEstate(){
        return mapper.selectList(null).stream()
                .map(this::beanToDTO)
                .collect(Collectors.toList());
    }

    public Estate findEstateByEstateName(String estateName){
        return mapper.selectEstateByEstateName(estateName);
    }

    //根据小区名取得小区所在城市
    public String findCityByEstateName(String estateName){
        return findEstateByEstateName(estateName).getCity();
    }

    //根据页码和选择条件取得页内容
    public PageDTO findPage(Integer pageNum, EstateSelect select){
        PageDTO<EstateDTO> pageDTO = new PageDTO<>();
        Page<EstateDTO> page = new Page<>(pageNum, 5);
        List<EstateDTO> result = mapper.selectPage(page, getWrapper(select)).stream()
                .map(this::beanToDTO).collect(Collectors.toList());
        pageDTO.setPage(page);
        pageDTO.setResult(result);
        return pageDTO;
    }

    public Wrapper<Estate> getWrapper(EstateSelect select){
        if(select == null) return null;

        Wrapper<Estate> wrapper = new EntityWrapper<>();
        boolean first = true, has = false;

        if(select.getCity() != null){
            has = true;
            for(String c : select.getCity()){
                if(first == true) first = false;
                else wrapper = wrapper.or();
                wrapper = wrapper.eq("city", c);
            }
        }

        if(select.getEstateName() != null){
            if(has) wrapper = wrapper.andNew();
            has = true;
            wrapper = wrapper.like("estate_name", select.getEstateName());
        }

        if(!select.getOrder().equals("default")){
            wrapper = wrapper.orderBy(select.getOrder(), false);
        }

        return wrapper;
    }

    public EstateDTO beanToDTO(Estate estate){
        EstateDTO dto = new EstateDTO();
        BeanUtils.copyProperties(estate, dto);
        return dto;
    }
}
